package client_core

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/client_core/service"
	"github.com/chicken-team-outside/chicken_transmission/model"
	"github.com/chicken-team-outside/chicken_transmission/sfs"
	"github.com/chicken-team-outside/chicken_transmission/utils"
	"os"
)

func walkLocalDirRecursive(ctx context.Context, deviceId uint64, deviceDir, localDir string, callback func(deviceParent, localParent string, f []os.FileInfo) error) error {
	client := GetSfsClient()
	if client == nil {
		return ErrSFSClientNotAvailable
	}
	localClient := client.GetLocal()
	if localClient == nil {
		return sfs.ErrNotSetLocalDriver
	}
	files, err := localClient.ListFiles(localDir)
	if err != nil {
		return err
	}
	err = callback(deviceDir, localDir, files)
	if err != nil {
		return err
	}
	for i := 0; i < len(files) && ctx.Err() == nil; i++ {
		if files[i].IsDir() {
			err = walkLocalDirRecursive(ctx, deviceId, utils.ConcatPath(deviceDir, files[i].Name()), utils.ConcatPath(localDir, files[i].Name()), callback)
			if err != nil {
				return err
			}
		}
	}
	return ctx.Err()
}

func (m *TaskRunnerMgr) runUploadDirScanTask(task *TaskWarp) error {
	return walkLocalDirRecursive(task.ctx, task.info.DeviceId, task.info.DevicePath, task.info.LocalPath, func(deviceParent, localParent string, f []os.FileInfo) error {
		tasks := make([]*model.Task, 0)
		for i := 0; i < len(f); i++ {
			t := &model.Task{
				Status:     model.TaskStatus_Waiting,
				Total:      f[i].Size(),
				DeviceId:   task.info.DeviceId,
				DevicePath: utils.ConcatPath(deviceParent, f[i].Name()),
				LocalPath:  utils.ConcatPath(localParent, f[i].Name()),
			}
			t.ParentId = task.info.Id
			t.TaskType = model.TaskType_UploadFile
			if ok, err := service.ExistsSameTask(t); err != nil {
				return err
			} else if ok {
				continue
			}
			tasks = append(tasks, t)
			task.AddTotal(1)
		}
		return m.fileRunner.AddTasks(tasks)
	})
}

func (m *TaskRunnerMgr) deleteUploadDirTaskCb(ids []int64) error {
	//TODO implement me
	panic("implement me")
}

func (m *TaskRunnerMgr) pauseUploadDirTaskCb(ids []int64) error {
	//TODO implement me
	panic("implement me")
}

func (m *TaskRunnerMgr) resumeUploadDirTaskCb(ids []int64) error {
	//TODO implement me
	panic("implement me")
}
